package com.xgr.wonderful.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xgr.wonderful.MainActivity;
import com.xgr.wonderful.R;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.utils.LocationUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.NetworkUtil;
import com.xgr.wonderful.activity.CommentActivity;
import com.xgr.wonderful.activity.base.BaseFragment;
import com.xgr.wonderful.adapter.StatusContentAdapter;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.entity.Status;

/**
 * 主fragment包含一个ViewPager ViewPager展示的fragment为这里的StatusContentFragment
 * 
 * @author lsj
 * 
 */

public class StatusContentFragment extends BaseFragment {

	// added by ethan 22-11-2014
	//这里是否应该使用LinkedLis
	private List<Status> mStatusList = new ArrayList<Status>();
	private StatusContentAdapter mStatusAdapter;

	private View contentView;
	private int currentIndex;
	private Integer lastStatusId = -1;

	private PullToRefreshListView mPullRefreshListView;
	private ListView actualListView;

	private TextView networkTips;
	private ProgressBar progressbar;

	public enum RefreshType {
		REFRESH, LOAD_MORE
	}

	private RefreshType mRefreshType = RefreshType.REFRESH;
	private int clickIndex = -1;

	private HttpProxy httpProxy;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOCATE_ING:
				LogUtils.i(TAG, "locate ing");
				setState(LOADING);
				break;
			case LOCATE_DONE:
				LogUtils.i(TAG, "locate done");
				// 保存下最新的位置
				sputil.recordLatestLocation(LocationUtils.getInstance()
						.getLatitude(), LocationUtils.getInstance()
						.getLongtitude());
				if (mStatusList == null || mStatusList.size() == 0) {
					fetchData();
				}
				break;
			case LOCATE_FAILED:
				LogUtils.i(TAG, "locate failed");
				ToastFactory.getToast(mContext, "定位失败，请查看是否联网或者打开定位权限").show() ;
				setState(LOADING_FAILED);
				break;
			default:
				break;
			}
		}
	};

	private static final int LOCATE_DONE = 0;
	private static final int LOCATE_ING = 1;
	private static final int LOCATE_FAILED = 2;

	// 检查定位是否完成的专用线程
	public class CheckThread implements Runnable {
		@Override
		public void run() {
			// 正在定位中，但是还没有定位结束
			mHandler.sendEmptyMessage(LOCATE_ING);
			while (LocationUtils.getInstance().getIsLocated() == false
					&& LocationUtils.getInstance().getIsLocating() == true);
			// 定位已经完成了，是否成功不知道
			if (LocationUtils.getInstance().getIsLocating() == false) {
				if (LocationUtils.getInstance().getIsLocated() == true) {
					mHandler.sendEmptyMessage(LOCATE_DONE); // 成功
				} else {
					mHandler.sendEmptyMessage(LOCATE_FAILED);
				}
			}
		}
	}

	public static BaseFragment newInstance(int index) {
		BaseFragment fragment = new StatusContentFragment();
		Bundle args = new Bundle();
		args.putInt("page", index);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		currentIndex = getArguments().getInt("page");
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (((MainActivity) getActivity()).getNeedAddStatusHome()) {
			addStatusFront(((MainActivity) getActivity()).getStatusNeedAdd());
			((MainActivity) getActivity()).setNeedAddStatusHome(false);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		contentView = inflater.inflate(R.layout.fragment_statuscontent, null);
		mPullRefreshListView = (PullToRefreshListView) contentView
				.findViewById(R.id.pull_refresh_list);
		networkTips = (TextView) contentView.findViewById(R.id.networkTips);
		progressbar = (ProgressBar) contentView.findViewById(R.id.progressBar);

		mPullRefreshListView.setMode(Mode.BOTH);
		// 设置上下拉时的显示文字 ,还可以设置图片
		ILoadingLayout startLabels = mPullRefreshListView
				.getLoadingLayoutProxy(true, false);
		startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
		startLabels.setRefreshingLabel("正在载入...");// 刷新时
		startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示
		//startLabels.setTextTypeface(tf)

		ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(
				false, true);
		endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
		endLabels.setRefreshingLabel("正在载入...");// 刷新时
		endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener2<ListView>() {
					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						mPullRefreshListView.setMode(Mode.BOTH);
						mRefreshType = RefreshType.REFRESH;
						fetchData();
					}

					@Override
					// 上拉事件
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						mPullRefreshListView.setMode(Mode.BOTH);
						mRefreshType = RefreshType.LOAD_MORE;
						fetchData();
					}
				});

		actualListView = mPullRefreshListView.getRefreshableView();
		mStatusAdapter = new StatusContentAdapter(mContext, mStatusList);
		actualListView.setAdapter(mStatusAdapter);
		// 进入评论页面
		actualListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				clickIndex = position - 1;
				Intent intent = new Intent();
				intent.setClass(getActivity(), CommentActivity.class);
				intent.putExtra("data", mStatusList.get(clickIndex));
				startActivityForResult(intent,
						Constant.REQUEST_CODE_COMMENT_NUM);
			}
		});
		new Thread(new CheckThread()).start();
		httpProxy = new HttpProxy();
		// } else { // 没有网络的情况
		if (NetworkUtil.isAvailable(mContext) == false) {
			mPullRefreshListView.setVisibility(View.VISIBLE);
			progressbar.setVisibility(View.GONE);
			networkTips.setVisibility(View.VISIBLE);
		}

		return contentView;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case Constant.REQUEST_CODE_COMMENT_NUM: //评论后增加
				int commentInc = data.getIntExtra(
						Constant.COMMENT_NUM_INCREAMENT, 0);
				if (commentInc != 0) {
					mStatusList.get(clickIndex).increaseCommentnum(commentInc);
					mStatusAdapter.notifyDataSetChanged();
				}
				break;

			default:
				break;
			}
		}

	}

	@Override
	public void onDetach() {
		super.onDetach();
		// 避免本地json文件太大
//		if (mStatusList.size() <= 50) {
//			Cache.putUserStatus(new Gson().toJson(mStatusList));
//		}
	}
	

	public void fetchData() {
		Status status = null;
		String statusJson = null;
		Double lat = LocationUtils.getInstance().getLatitude();
		Double lng = LocationUtils.getInstance().getLongtitude();
		if (mRefreshType == RefreshType.REFRESH) {
			status = new Status(null, Integer.valueOf(0),
					Constant.NUMBERS_PER_PAGE, Long.valueOf(10000), lat, lng);
		} else {
			status = new Status(null, lastStatusId, Constant.NUMBERS_PER_PAGE,
					Long.valueOf(10000), lat, lng);
		}
		try {
			statusJson = new Gson().toJson(status);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (statusJson != null) {
			httpProxy.queryStatus(statusJson, new IHttpRequestListener() {

				@Override
				public void OnHttpRequestSuccessful(String result, int errCode) {
					handleData(result, errCode);
				}

				@Override
				public void OnHttpRequestStart() {
					setState(LOADING);
				}

				@Override
				public void OnHttpRequestFailure(String info) {
					ToastFactory.getToast(mContext, "更新数据失败，请检查网络环境后重试").show();
					setState(LOADING_FAILED);
					mPullRefreshListView.onRefreshComplete();
				}
			});
		}
	}

	private static final int LOADING = 1;
	private static final int LOADING_COMPLETED = 2;
	private static final int LOADING_FAILED = 3;
	private static final int LOADING_NO_MORE_DATA = 4;

	public void setState(int state) {
		switch (state) {
		case LOADING: // 正在定位中或者数据正在拉取中
			if (mStatusList == null || mStatusList.size() == 0) {
				networkTips.setVisibility(View.GONE);
				progressbar.setVisibility(View.VISIBLE);
			}
			break;
		case LOADING_COMPLETED:
			networkTips.setVisibility(View.GONE);
			progressbar.setVisibility(View.GONE);
			mPullRefreshListView.setVisibility(View.VISIBLE);
			break;
		case LOADING_FAILED:
			if (mStatusList == null || mStatusList.size() == 0) {
				networkTips.setVisibility(View.VISIBLE);
				networkTips.setText("您可能没有网络或者禁止了定位功能") ;
			}
			mPullRefreshListView.setVisibility(View.VISIBLE);
			progressbar.setVisibility(View.GONE);
			break;
		case LOADING_NO_MORE_DATA:
			networkTips.setVisibility(View.GONE);
			mPullRefreshListView.setVisibility(View.VISIBLE);
			progressbar.setVisibility(View.GONE);
		default:
			break;
		}
	}

	private void handleData(String result, int errCode) {
		List<Status> queryList = null;
		if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS) {
			try {
				queryList = new Gson().fromJson(result,
						new TypeToken<List<Status>>() {
						}.getType());
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (queryList != null && queryList.size() != 0) {
				if (mRefreshType == RefreshType.REFRESH) {
					mStatusList.clear();
				}
				if (queryList.size() < Constant.NUMBERS_PER_PAGE) {
					ToastFactory.getToast(mContext, "没有更多数据了").show();
				}
				mStatusList.addAll(queryList);
				lastStatusId = mStatusList.get(mStatusList.size() - 1).getId();
				mStatusAdapter.notifyDataSetChanged();
			} else if (queryList != null && queryList.size() == 0) {
				if (lastStatusId > 0) {
					// 说明 有status且不是第一次拉取，然后没有数据了
					ToastFactory.getToast(mContext, "没有更多数据了").show();
				} else {
					// 本来就没有评论，所以为0， 不用显示
					ToastFactory.getToast(mContext, "暂时还没有数据").show();
				}
			}
			setState(LOADING_COMPLETED);
			mPullRefreshListView.onRefreshComplete();
		} else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
			ToastFactory.getToast(mContext, "加载数据失败").show();
			setState(LOADING_FAILED);
			mPullRefreshListView.onRefreshComplete();
		}
	}

	/**
	 * 发表状态，将新的状态添加到最前面，实际上是有问题的，如果在这个之间别人 也有发送的新消息。好的办法是直接再次refresh
	 * @param status
	 */
	public void addStatusFront(Status status) {
		mStatusList.add(0, status);
		mStatusAdapter.notifyDataSetChanged();
	}

	public List<Status> getLocalStatus() {
		return mStatusList;
	}

	/**
	 * 没有网时，再打开自动 刷新一下，可以不要的
	 */
	public void refresh() {
		//一般情况下是没有网络导致的
		if (mStatusList.size()==0){
			mRefreshType = RefreshType.REFRESH;
			fetchData();
		}
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
		//恢复时，如果之前没有数据，则再次拉取一次数据 
		LogUtils.i(TAG, "refresh in onResume") ;
		refresh() ;
	}
	
}
